package com.cee.admin.config.converter;

import com.cee.common.constant.AppConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author wsz
 * @create 2023/3/9
 */
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String s) {
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat(AppConstants.DEFAULT_DATETIME_FORMAT);
            try {
                ZoneId zoneId = ZoneId.systemDefault();
                //String转成Date类型
                Date date = sdf1.parse(s);
                Instant instant = date.toInstant();
                return instant.atZone(zoneId).toLocalDateTime();
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException("转换日期格式时发生错误");
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("转换日期格式时发生错误");
        }
    }
}